/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aviso.facade;

import aviso.entity.Advert;
import aviso.entity.ImageFile;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author avgusti
 */
@Stateless
public class ImageFileFacade extends AbstractFacade<ImageFile> {

    @PersistenceContext(unitName = "aviso")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ImageFileFacade() {
        super(ImageFile.class);
    }

    public Long getCountNameAndUser(String name, Long userid) {
        Long c = em.createNamedQuery("File.countNameAndUser", Long.class).setParameter("name", name).setParameter("userid", userid).getSingleResult();
        return c;
    }
    //File.listByUser

    public List<ImageFile> listByUser(Long userid) {
        List<ImageFile> fl = em.createNamedQuery("File.listByUser", ImageFile.class).setParameter("userid", userid).getResultList();
        return fl;
    }

    @Override
    public void remove(ImageFile entity) {
       entity = em.createNamedQuery("File.loadEager", ImageFile.class).setParameter("fileid", entity.getId()).getSingleResult();
        for (Advert a : entity.getAdverts()) {
            a.getFiles().remove(entity);
            em.merge(a);
            em.persist(a);
        }
        entity.getUserName().setAvatar(null);
        em.persist(entity.getUserName());
        super.remove(entity);
        em.flush();
     }
    
    
}
